package com.atguigu.juc.date108;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: shenhao
 * @CreatTime: 2024/10/8 16:59
 * @Version: 1.0
 * 3个卖票的按照线程池的写法
 */
public class SaleTicketPool {
    public static void main(String[] args) {
        SaleTicket saleTicket = new SaleTicket();
        //ExecutorService threadPool = Executors.newFixedThreadPool(3);
        ExecutorService threadPool = new ThreadPoolExecutor(3,
                3,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>()
        , new ThreadPoolExecutor.CallerRunsPolicy());
        try {
            for (int i = 0; i < 50; i++) {
                threadPool.execute(()->{
                    saleTicket.saleTicket();
                });
            }
        }finally {
            threadPool.shutdown();
        }
    }
}

class SaleTicket {
    private Integer num = 50;
    Lock lock = new ReentrantLock();
    public void saleTicket(){
        lock.lock();
        try {
            if(num>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(num--)+"张票\t还剩下了"+num+"张票");
            }
        }finally {
            lock.unlock();
        }
        try {// 睡眠事件,要写到锁外边
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
